package org.example.carplatoon.Interceptor;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.example.carplatoon.common.R;
import org.example.carplatoon.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        log.info("拦截到请求：{}", url);
        //放行登录请求
        if (url.contains("/login")) {
            log.info("放行登录请求");
            return true;
        }

        //令牌不存在
        String jwt = request.getHeader("Authorization");
        if (!StringUtils.hasLength(jwt)) {
            log.info("解析令牌失败");
            R error = R.error("未登录");
            String notlogin = JSONObject.toJSONString(error);
            response.setContentType("text/html; charset=UTF-8");
            response.getWriter().write(notlogin);
            return false;
        }

        try {
            JwtUtils.checkToken(jwt);

        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败");
            R error = R.error("未登录");
            String notlogin = JSONObject.toJSONString(error);
            response.setContentType("text/html; charset=UTF-8");
            response.getWriter().write(notlogin);
            return false;
        }
        log.info("令牌解析成功");
        return true;
    }
}

